package com.ruyuan.payment.server.service;

import com.ruyuan.payment.server.domain.OrderPay;
import com.ruyuan.payment.server.domain.OrderPayExample;
import com.ruyuan.payment.server.enums.OrderPayStatusEnum;
import com.ruyuan.payment.server.mapper.OrderPayMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

@Service
public class PayCloseService {

    private static final Logger LOG = LoggerFactory.getLogger(PayCloseService.class);

    @Resource
    private OrderPayMapper orderPayMapper;

    @Resource
    private AccountService accountService;

    public void close(OrderPay orderPayDB) {
        LOG.info("关闭本地订单开始：orderPayDB：{}", orderPayDB);

        LOG.info("更新支付订单为已关闭：orderPayDB：{}", orderPayDB);
        if (updateOrderPay(orderPayDB)) {
            return;
        }

        if (orderPayDB.getAccountAmount().compareTo(BigDecimal.ZERO) > 0) {
            accountService.unfreeze(orderPayDB.getMemberId(), orderPayDB.getAccountAmount(), orderPayDB.getPayNo());
        }
    }

    private boolean updateOrderPay(OrderPay orderPayDB) {
        Date now = new Date();
        orderPayDB.setStatus(OrderPayStatusEnum.CLOSE.getCode());
        orderPayDB.setUpdatedTime(now);
        OrderPayExample orderPayExample = new OrderPayExample();
        orderPayExample.createCriteria().andIdEqualTo(orderPayDB.getId())
                .andStatusEqualTo(OrderPayStatusEnum.INIT.getCode());
        int i = orderPayMapper.updateByExample(orderPayDB, orderPayExample);
        if (i == 0) {
            LOG.info("防重拦截：支付订单状态非初始：payNo：{}，status：{}", orderPayDB.getPayNo(), orderPayDB.getStatus());
            return true;
        }
        return false;
    }
}
